package cn.learn.barcode;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码工具类
 * https://www.jianshu.com/p/05e9ee773898
 * <p>
 * 生成带logo的二维码
 * https://www.jianshu.com/p/0cd6c56ea725
 *
 * @author huangyezhan
 * @version 1.0
 * @date 2021年06月09日0:37
 */
@Slf4j
public class QRCodeUtil {

    private static final int IMAGE_WIDTH      = 300;
    private static final int IMAGE_HEIGHT     = 300;
    private static final int IMAGE_HALF_WIDTH = IMAGE_WIDTH / 2;
    private static final int FRAME_WIDTH      = 2;

    /**
     * 二维码参数
     */
    private static final Map<EncodeHintType, Object> ENCODE_HINTS = new HashMap<>();
    private static final Map<DecodeHintType, Object> DECODE_HINTS = new HashMap<>();

    static {
        // 字符编码
        ENCODE_HINTS.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 容错等级 L、M、Q、H 其中 L 为最低, H 为最高
        ENCODE_HINTS.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 二维码与图片边距
        ENCODE_HINTS.put(EncodeHintType.MARGIN, 2);

        DECODE_HINTS.put(DecodeHintType.CHARACTER_SET, "UTF-8");
    }

    /**
     * 生成二维码
     *
     * @param content 二维码内容
     * @param width   宽
     * @param height  高
     */
    public static BufferedImage encodeQRcode(String content, int width, int height) throws WriterException {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, ENCODE_HINTS);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

    /**
     * 生成带有logo标志的二维码
     *
     * @param context  二维码存储内容
     * @param width    二维码宽度
     * @param height   二维码高度
     * @param logoPath 二维码logo路径
     * @return 返回二维码
     */
    public static BufferedImage encodeLogoQRcode(String context, int width, int height, String logoPath) {
        BufferedImage logo = null;
        try {
            // 读取Logo图像
            BufferedImage logoImage = scale(logoPath, width, height, true);
            int[][]       srcPixels = new int[IMAGE_WIDTH][IMAGE_HEIGHT];
            for (int i = 0; i < logoImage.getWidth(); i++) {
                for (int j = 0; j < logoImage.getHeight(); j++) {
                    srcPixels[i][j] = logoImage.getRGB(i, j);
                }
            }
            BitMatrix bitMatrix = new MultiFormatWriter().encode(context, BarcodeFormat.QR_CODE, width, height, ENCODE_HINTS);
            // 二维矩阵转为一维像素数组
            int halfW = bitMatrix.getWidth() / 2;
            int halfH = bitMatrix.getHeight() / 2;

            int[] pixels = new int[width * height];

            for (int y = 0; y < bitMatrix.getHeight(); y++) {
                for (int x = 0; x < bitMatrix.getWidth(); x++) {
                    boolean flag = (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
                            && x < halfW - IMAGE_HALF_WIDTH + FRAME_WIDTH
                            && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH
                            && y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH
                    ) || (x > halfW + IMAGE_HALF_WIDTH - FRAME_WIDTH
                            && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
                            && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH
                            && y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH
                    ) || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
                            && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
                            && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH
                            && y < halfH - IMAGE_HALF_WIDTH + FRAME_WIDTH
                    ) || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
                            && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
                            && y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH
                            && y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH);

                    // 读取图片
                    if (x > halfW - IMAGE_HALF_WIDTH
                            && x < halfW + IMAGE_HALF_WIDTH
                            && y > halfH - IMAGE_HALF_WIDTH
                            && y < halfH + IMAGE_HALF_WIDTH) {

                        pixels[y * width + x] = srcPixels[x - halfW + IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH];
                    } else if (flag) {
                        // 在图片四周形成边框
                        pixels[y * width + x] = 0xfffffff;
                    } else {
                        // 此处可以修改二维码的颜色，可以分别制定二维码和背景的颜色；
                        pixels[y * width + x] = bitMatrix.get(x, y) ? 0xff000000 : 0xfffffff;
                    }
                }
            }
            logo = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            logo.getRaster().setDataElements(0, 0, width, height, pixels);
        } catch (WriterException e) {
            log.error("生成二维码异常：{}", e.getMessage());
        }
        return logo;
    }

    /**
     * 对图片进行缩放
     *
     * @param imgPath   图片路径
     * @param width     图片缩放后的宽度
     * @param height    图片缩放后的高度
     * @param hasFiller 是否补白
     * @return 图片
     */
    private static BufferedImage scale(String imgPath, int width, int height, boolean hasFiller) {
        // 缩放比例
        double        ratio    = 0.0;
        File          file     = new File(imgPath);
        BufferedImage srcImage = null;
        try {
            srcImage = ImageIO.read(file);
        } catch (IOException e) {
            log.error("生成二维码，缩放二维码异常：{}", e.getMessage());
        }
        Image finalImage;
        finalImage = srcImage.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
        // 计算比例
        if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
            if (srcImage.getHeight() > srcImage.getWidth()) {
                ratio = (new Integer(height)).doubleValue() / srcImage.getHeight();
            } else {
                ratio = (new Integer(width)).doubleValue() / srcImage.getWidth();
            }
            AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
            finalImage = op.filter(srcImage, null);
        }
        // 补白
        if (hasFiller) {
            BufferedImage image   = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D    graphic = image.createGraphics();
            graphic.setColor(Color.white);
            graphic.fillRect(0, 0, width, height);
            if (width == finalImage.getWidth(null)) {
                graphic.drawImage(finalImage, 0, (height - finalImage.getHeight(null)) / 2, finalImage.getWidth(null), finalImage.getHeight(null), Color.white, null);
            } else {
                graphic.drawImage(finalImage, (width - finalImage.getWidth(null)) / 2, 0, finalImage.getWidth(null), finalImage.getHeight(null), Color.white, null);
                graphic.dispose();
                finalImage = image;
            }
        }
        return (BufferedImage) finalImage;
    }

    /**
     * 解析读取二维码
     *
     * @param image 二维码图片
     * @return 返回二维码解析结果
     */
    public static String decodeQRcode(BufferedImage image) {
        String qrCodeText = null;
        try {
            LuminanceSource source       = new BufferedImageLuminanceSource(image);
            Binarizer       binarizer    = new HybridBinarizer(source);
            BinaryBitmap    binaryBitmap = new BinaryBitmap(binarizer);

            // 对图像进行解码
            Result result = new MultiFormatReader().decode(binaryBitmap, DECODE_HINTS);
            qrCodeText = result.getText();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        return qrCodeText;
    }

    public static String decodeQRcode(String path) {
        try {
            BufferedImage image = ImageIO.read(new File(path));
            return decodeQRcode(image);
        } catch (IOException e) {
            log.error("根据路径获取二维码图片异常：{}", e.getMessage());
            return null;
        }
    }

    public static void main(String[] args) {
        /*BufferedImage image = encodeQRcode("https://www.baidu.com", 300, 300);
        ImageIO.write(image, "jpg", new File("D://abc7.jpg"));*/

        System.out.println(decodeQRcode("D://abc10.jpg"));
    }

}
